<template>
  <!--文件的上传 编辑回显 和下载  -->
  <div>
    <el-row v-if="!readOnly" :gutter="10">
      <el-col v-if="status !== '2'" :span="18">
        <el-upload
          ref="fileupload"
          class="upload-demo"
          action="#"
          :http-request="uploadFile"
          :before-upload="beforeUploadFile"
          :on-preview="onUploadPreview"
          :on-success="onUploadFileSuccess"
          :on-error="onUplodeFileError"
          :before-remove="handleBeforeRemove"
          :on-remove="handleRemove"
          :on-change="handleChange"
          multiple
          :show-file-list="false"
          :file-list="fileList"
          :limit="5"
          :on-exceed="handleExceed"
        >
          <el-button size="mini">点击上传</el-button>
          <span slot="tip" class="el-upload__tip" style="padding-left:10px;color:red;font-size: 12px">(文件不超过30MB)</span>
        </el-upload>
      </el-col>
    </el-row>
    <!-- fileList -->
    <el-table :size="detailSize" :data="tableData" class="definite-list">
      <el-table-column align="center" prop="fileName" label="文件名称" min-width="150" />
      <el-table-column align="center" prop="createTime" label="上传时间" min-width="140" />
      <el-table-column v-if="status !== '2'" align="center" prop="address" label="操作" min-width="100">
        <template slot-scope="scope">
          <el-button v-if="!readOnly && !isDel" size="mini" @click="handleBeforeRemove(scope.row, scope.$index)">删除</el-button>
          <el-button size="mini" @click="downFile(scope.row.fileId, scope.row.fileName)">下载</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
// 附件上传
import { fileUpload, fileDownLoad } from '@/api/common/upload.js'
export default {
  name: 'FileUpload',
  components: {
  },
  props: {
    // 上传的附件回显
    editFileList: {
      type: Array,
      // 当为数组类型设置默认值时必须使用数组返回
      default: function() {
        return []
      }
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    status: {
      type: String,
      default: ''
    },
    isDel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileList: [], // 存放编辑 文件的集合（附件回显）
      fileListData: [],
      tableData: [], // 附件表格
      percent: '', // 上传进度
      deleteFileIds: [] // 删除的文件id
    }
  },
  computed: {},
  watch: {
    editFileList: function(val) {
      if (val !== undefined && val.length > 0) {
        this.tableData = JSON.parse(JSON.stringify(val))
        this.fileList = JSON.parse(JSON.stringify(val))
      } else {
        this.fileList = []
        this.tableData = []
      }
    },
    fileList() {
      this.changeFileList()
    }
  },
  mounted() {
  },
  methods: {
    // 附件上传之前调用的函数，控制附件上传的大小和格式
    beforeUploadFile(file) {
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.msgError('上传文件大小不能超过 30MB!')
        return false
      }
      return true
    },
    // 自定义文件上传
    uploadFile(item) {
      // 传入文件的类型
      const formData = new FormData()
      formData.append('file', item.file)
      fileUpload(formData)
        .then(res => {
          item.onSuccess(res)
        })
        .catch(err => {
          item.onError(err)
        })
    },
    // 上传的文件改变时调用的方法，附件新增 附件删除都会调用
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    // 上传成功的回调
    onUploadFileSuccess(res, file) {
      if (res) {
        const fileData = {
          fileId: res.data.fileId,
          createTime: res.data.uploadDate,
          fileName: res.data.fileName
        }
        this.tableData.push(fileData) // 填充上传文件列表
        this.msgSuccess('上传成功')
      } else {
        this.msgError(res.message)
      }
    },
    // 限制文件上传的个数
    handleExceed(files, fileList) {
      this.msgWarning(
        `当前限制选择 5 个文件，本次选择了 ${
          files.length
        } 个文件，共选择了 ${files.length + fileList.length} 个文件`
      )
    },
    // 文件上传失败的回调
    onUplodeFileError(err, file, fileList) {
      if (err.message === 'Network Error') {
        this.msgError('上传文件过大或者磁盘已满')
      } else {
        this.msgError('上传文件过大或者磁盘已满')
      }
    },
    // 下载文件
    downFile(id, name) {
      fileDownLoad(id).then(res => {
        if (!res) { return }
        const url = window.URL.createObjectURL(new Blob([res]))
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', name)
        document.body.appendChild(link)
        link.click()
      })
    },
    // 上传的文件预览下载
    onUploadPreview(file) {
      console.log(file)
    },
    // 文件删除之前操作
    handleBeforeRemove(file, fileList) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 在这里真正的处理图片列表
          this.handleRemove(file, fileList)
        })
        .catch(() => {
          this.msgWarning('已取消删除')
        })
      return false // 这是重点,不管上面的操作结果如何都返回false
    },
    // 文件删除
    handleRemove(file, fileList) {
      // eslint-disable-next-line no-prototype-builtins
      const isRe = file.hasOwnProperty('response')
      let fileId = null
      if (isRe) {
        fileId = file.response.data.fileId
      } else {
        fileId = file.fileId
      }
      if (fileId) {
        this.deleteFileIds.push(fileId)
        this.tableData.splice(this.tableData.findIndex(item => item.fileId === fileId), 1)
        this.fileList.splice(this.fileList.findIndex(item => item.fileId === fileId), 1)
      }
    },
    // 把上传的附件信息回传给父组件
    changeFileList() {
      const deleteFileIds = this.deleteFileIds
      const fileList = this.tableData
      this.$emit('getFileList', fileList, deleteFileIds)
    }
  }
}
</script>

<style lang="scss">
  .el-upload__tip{
    padding-left:10px;
    color:red;
    font-size: 12px
  }
</style>
